Page({
  data: {
    dialogVisible: false,
    houseList: [],
    isEmpty: true
  },
  onShow () {
    this.getHouseList()
  },
  async getHouseList () {
    // 调用接口
    const { code, data: houseList } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast()
    this.setData({
      houseList,
      isEmpty: houseList.length === 0
    })
  },
  swipeClose (ev) {
    const { position, instance } = ev.detail

    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true
      })
      this.cellId = ev.mark.id
      this.cellIndex = ev.mark.index
      // swiper-cell 滑块关闭
      instance.close()
    }
  },
  dialogClose (ev) {
    if(ev.detail === 'confirm') this.deleteHouse()
  },
  async deleteHouse () {
    // 检测id是否存在
    if (!this.cellId) return wx.utils.toast('参数有误!')
    // 调用接口
    const { code } = await wx.http.delete('/room/' + this.cellId)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast()
    // 从 AppData 中将删除的房屋从数组移除
    this.data.houseList.splice(this.cellIndex, 1)
    // 渲染数据
    this.setData({
      houseList: this.data.houseList,
      isEmpty: this.data.houseList.length === 0
    })
  },
  goDetail (ev) {
    const id = ev.mark.id
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + id
    })
  },

  addHouse () {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index'
    })
  }
})
